package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderProcessTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时的代付款订单
     * 1分钟检查一次看是否有订单超时
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOut(){
        log.info("{} 检查是否有超时代付款订单", LocalDateTime.now());
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> orders = orderMapper.getStatusAndOrderTime(status, orderTime);
        if(orders != null && orders.size() > 0) {
            orders.forEach(orderDB -> {
                Orders order = new Orders();
                order.setId(orderDB.getId());
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("用户代付款订单超时");
                orderMapper.update(order);
            });
        }
    }

    /**
     * 处理完成的派送中订单
     * 凌晨1点，将昨天还在派送中的订单变成完成状态
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDelivery() {
        log.info("{}，将昨天还在派送中的订单变成完成状态", LocalDateTime.now());
        // 查询状态为派送中，并且下单时间为昨天的订单
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> orders = orderMapper.getStatusAndOrderTime(status, orderTime);
        if(orders != null && orders.size() > 0) {
            orders.forEach(orderDB -> {
                Orders order = new Orders();
                order.setId(orderDB.getId());
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
